<template>
    <el-form class="login-form"
             status-icon
             :rules="loginRules"
             ref="loginForm"
             :model="loginForm"
             label-width="0">
        <!-- 账号 -->
        <el-form-item prop="username">
            <el-input size="small"
                      @keyup.enter.native="handleLogin"
                      v-model="loginForm.username"
                      maxlength="20"
                      auto-complete="off"
                      :placeholder="$t('login.username')">
                <i slot="prefix"
                   class="icon-yonghu"></i>
            </el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
            <el-input size="small"
                      @keyup.enter.native="handleLogin"
                      :type="passwordType"
                      v-model="loginForm.password"
                      maxlength="20"
                      auto-complete="off"
                      :placeholder="$t('login.password')">
                <i class="el-icon-view el-input__icon"
                   slot="suffix"
                   @click="showPassword"></i>
                <i slot="prefix"
                   class="icon-mima"></i>
            </el-input>
        </el-form-item>
        <!-- 验证码输入框 -->
        <el-form-item prop="code">
            <el-row :span="24">
                <el-col :span="16">
                    <el-input size="small"
                              @keyup.enter.native="handleLogin"
                              :maxlength="code.len"
                              v-model="loginForm.code"
                              auto-complete="off"
                              :placeholder="$t('login.code')">
                        <i slot="prefix"
                           class="icon-yanzhengma"></i>
                    </el-input>
                </el-col>
                <!-- 验证码图片-->
                <el-col :span="8">
                    <div class="login-code">
                        <span class="login-code-img" @click="refreshCode" v-if="code.type == 'text'">{{ code.value }}</span>
                        <img :src="code.src"
                             class="login-code-img"
                             @click="refreshCode"
                             v-else/>
                        <!-- <i class="icon-shuaxin login-code-icon" @click="refreshCode"></i> -->
                    </div>
                </el-col>
            </el-row>

        </el-form-item>

        <el-form-item>
            <el-button type="primary"
                       size="small"
                       @click.native.prevent="handleLogin"
                       class="login-submit">{{ $t('login.submit') }}
            </el-button>
        </el-form-item>
        <!-- 行为验 -->
        <div id="captcha-box" v-show="captchaShow"></div>
    </el-form>
</template>

<script>
import {randomLenNum} from "@/util/util";
import {mapGetters} from "vuex";
import {basePath, proxyPath} from "@/config/env";

export default {
    name: "userlogin",
    data() {
        // 验证码验证
        const validateCode = (rule, value, callback) => {
            if (this.code.value != value) {
                // this.loginForm.code = "";
                // this.refreshCode();
                callback(new Error("请输入正确的验证码"));
            } else {
                callback();
            }
        };
        return {
            captchaShow: false,
            globalTAC: null,
            loginForm: {
                username: "",
                password: "",
                code: "",
                redomStr: ""
            },
            checked: false,
            code: {
                src: "",
                value: "",
                len: 4,
                type: "text"
            },
            loginRules: {
                username: [
                    {required: true, message: "请输入用户名", trigger: "blur"}
                ],
                password: [
                    {required: true, message: "请输入密码", trigger: "blur"},
                    {min: 6, message: "密码长度最少为6位", trigger: "blur"}
                ],
                code: [
                    {required: true, message: "请输入验证码", trigger: "blur"},
                    {min: 4, max: 4, message: "验证码长度为4位", trigger: "blur"},
                    {required: true, trigger: "blur", validator: validateCode}
                ]
            },
            passwordType: "password"
        };
    },
    created() {
        this.refreshCode();
    },
    mounted() {
    },
    computed: {
        ...mapGetters(["tagWel"])
    },
    props: [],
    methods: {
        // 刷新验证码
        refreshCode() {
            this.loginForm.redomStr = randomLenNum(this.code.len, true);
            this.code.type == "text"
                ? (this.code.value = randomLenNum(this.code.len))
                : (this.code.src = `${this.codeUrl}/${this.loginForm.redomStr}`);
            // this.loginForm.code = this.code.value;
        },
        // 显示密码
        showPassword() {
            this.passwordType == ""
                ? (this.passwordType = "password")
                : (this.passwordType = "");
        },
        // 提交
        handleLogin() {
            this.$refs.loginForm.validate(async valid => {
                if (valid) {
                    let isLoginEnvironment = await this.isLoginEnvironment();
                    if (isLoginEnvironment) {
                        this.$store.dispatch("LoginByUsername", this.loginForm).then(() => {
                            this.$router.push({path: this.tagWel.value});
                        });
                    } else {
                        this.handleCaptchaLogin();
                    }
                }
            });
        },
        // 先进行行为验在登录
        handleCaptchaLogin() {
            this.captchaShow = true;
            this.globalTAC = new TAC({
                // 生成接口
                requestCaptchaDataUrl: proxyPath + "/api/open/captcha/gen?type=SLIDER",
                // 验证接口
                validCaptchaUrl: proxyPath + "/api/open/captcha/check",
                // 验证码绑定的div块
                bindEl: "#captcha-box",
                // 验证成功回调函数
                validSuccess: (res, c, tac) => {
                    // 销毁验证码
                    tac.destroyWindow();
                    // 设置行为验Id
                    this.loginForm.captchaId = res.data.validToken;
                    // 调用登录方法
                    this.$store.dispatch("LoginByUsername", this.loginForm).then(() => {
                        this.$router.push({path: this.tagWel.value});
                    });
                }
            }, {
                logoUrl: null
            }).init();
        },
        // 判断和上一次的登录环境是否相同
        async isLoginEnvironment() {
            let data = {
                "channel": "ACCOUNT_OR_PHONE_PASSWORD",
                data: {
                    username: this.loginForm.username,
                    password: Base64.encode(this.loginForm.password)
                }
            }
            let res = await this.crud.post('/api/admin/sys/login/isLoginEnvironment', data);
            return res.data.data;
        }
    }
};
</script>

<style>
#captcha-box {
    position: absolute;
    top: 24%;
    left: 19%;
}
</style>
